
package br.unirio.bsi.dsw.AuctionSite.action;

import flexjson.JSONSerializer;

import org.apache.struts.action.*;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.unirio.bsi.dsw.AuctionSite.beans.loginForm;
import br.unirio.bsi.dsw.AuctionSite.model.dao.GenericDAO;

import br.unirio.bsi.dsw.AuctionSite.beans.albumForm;
import br.unirio.bsi.dsw.AuctionSite.beans.formBeanAL;
import br.unirio.bsi.dsw.AuctionSite.beans.formBeanM;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class albumAction extends Action 
{
  @Override
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request, 
                               HttpServletResponse response) throws Exception 
  {      
    // pega a session
    HttpSession session = request.getSession();  
    
    // check logged
    loginForm lf = (loginForm)session.getAttribute("loginForm"); 
    if( lf == null || !lf.isLogged() )
      return null;
    
    // pega instancia do DAO
    
    GenericDAO gD = GenericDAO.getInstance(getResources(request).getMessage("DB_NAME"));
    
    // copy
    albumForm aF = (albumForm)form;
    

    // parameter
    String selPage = aF.getSelectedPage();
    String selArt = aF.getSelectedArtista();
    String selEst = aF.getSelectedEstilo(); 
    String search = aF.getSearch();
    if( selArt != null && !selArt.equals("") ) 
    {
      gD.retrieveAll( "SELECT DISTINCT a.*, b.nome as artistaNome " +
                      "FROM   Album a, Artista b " +
                      "WHERE  a.idartista = " + selArt +
                      " AND   b.id = a.idartista " +
                      "ORDER BY a.url DESC " +              
                      "OFFSET " + selPage +
                      " LIMIT 15", 
                      formBeanAL.class, aF.getAlbums() );      
    }
    else    
    if( selEst != null && !selEst.equals("") ) 
    {        
      gD.retrieveAll( "SELECT DISTINCT a.*, b.nome as artistaNome " +
                      "FROM Album a, EstiloArtista ea, Artista b " +
                      "WHERE a.idartista = ea.idartista " +
                      "AND   ea.idestilo = " + selEst +
                      " AND   b.id = a.idartista " +   
                      "ORDER BY a.url DESC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 15",       
                      formBeanAL.class, aF.getAlbums() );    
    }
    else    
    if( search != null && !search.equals("") ) 
    {        
      gD.retrieveAll( "SELECT DISTINCT a.*, b.nome as artistaNome " +
                      "FROM Album a, Artista b, Musica m " +
                      "WHERE a.idartista = b.id " +
                      "AND m.idalbum = a.id " +
                      "AND (a.nome ~* '"+ search + "'  " +
                        "OR b.nome ~* '"+ search + "'  " +
                        "OR m.nome ~* '"+ search + "') " +
                      "ORDER BY a.url DESC " +                            
                      "OFFSET " + selPage +
                      " LIMIT 15", formBeanAL.class, aF.getAlbums() );        
    }
    
    // database is mess do some anti repeat clearance
    Set<formBeanAL> set = new HashSet<formBeanAL>(aF.getAlbums());
    aF.setAlbums( new ArrayList<formBeanAL>( set ) );

    // pega musicas
    for( formBeanAL a : aF.getAlbums() ) 
    {      
      gD.retrieveAll( "SELECT DISTINCT m.* " +
                      "FROM Album a, Musica m " +
                      "WHERE a.id = m.idalbum " +
                      "AND   a.id = " + a.getID(),
                      formBeanM.class, aF.getFieldMusica().getMusicas() );
             
      if( a.getUrl() == null || a.getUrl().isEmpty() )
        a.setUrl("./images/notfound.gif");
    }    
    
      
    String jsonAlbums = new JSONSerializer()
                            .exclude("class").exclude("IDArtista")
                            .serialize( aF.getAlbums() );
    
    jsonAlbums = "({\"album\":" + jsonAlbums + ",";

    String jsonMusicas = new JSONSerializer()
                             .exclude("class")
                             .serialize( aF.getFieldMusica().getMusicas() );
    
    jsonMusicas = "\"musicas\":" + jsonMusicas + "})";
        
    response.getWriter().write( jsonAlbums + jsonMusicas );
    response.getWriter().flush();
    
    return null;
  }
}
